define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            function debounce(handle, delay) {
                let time = null;
                return function () {
                    let self = this,
                        arg = arguments;
                    clearTimeout(time);
                    time = setTimeout(function () {
                        handle.apply(self, arg);
                    }, delay)
                }
            }
            var indexPage = new Vue({
                el: "#indexPage",
                data() {
                    return {
                        indexList: [],
                        currentPage: 1,
                        totalPage: 0,
                        offset: 0,
                        limit: 10,
                        isAjax: false,
                        tableAjax: false,
                        expressDetail: null,
                        expressData: {
                            express_name: '',
                            express_code: '',
                            express_no: ''
                        },
                        expressDataInit: {
                            express_name: '',
                            express_code: '',
                            express_no: ''
                        },
                        expressDialog: false,
                        expressCompany: [],
                        selectSearchKey: '',
                        selectOffset: 0,
                        selectLimit: 6,
                        selectCurrentPage: 1,
                        selectTotalPage: 0,

                        searchForm: {
                            form_1_key: "store_id",
                            form_1_value: "",
                            form_2_key: "express_name",
                            form_2_value: "",
                        },
                        searchFormInit: {
                            form_1_key: "store_id",
                            form_1_value: "",
                            form_2_key: "express_name",
                            form_2_value: "",
                        },
                        searchOp: {
                            store_id: "=",
                            store_name: "like",
                            express_name: "like",
                            express_no: "=",
                        },
                    }
                },
                mounted() {
                    this.getIndexList()
                },
                methods: {
                    getIndexList() {
                        let that = this;
                        if (!that.isAjax) {
                            that.tableAjax = true;
                        }
                        let filter = {}
                        let op = {}
                        for (key in that.searchForm) {
                            if (key == 'form_1_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_1_key] = that.searchForm[key];
                                }
                            } else if (key == 'form_2_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_2_key] = that.searchForm[key];
                                }
                            }
                        }
                        for (key in filter) {
                            op[key] = that.searchOp[key]
                        }
                        Fast.api.ajax({
                            url: 'groupon/order/store_express/index',
                            loading: false,
                            type: 'GET',
                            data: {
                                offset: that.offset,
                                limit: that.limit,
                                op: JSON.stringify(op),
                                filter: JSON.stringify(filter)
                            }
                        }, function (ret, res) {
                            that.indexList = res.data.rows;
                            that.totalPage = res.data.total;
                            that.isAjax = false;
                            that.tableAjax = false;
                            return false;
                        }, function (ret, res) {
                            that.isAjax = false;
                            that.tableAjax = false;
                        })
                    },
                    operation(type, row) {
                        let that = this;
                        switch (type) {
                            case 'add':
                                Fast.api.open(`groupon/order/store_express/add`, '备货', {
                                    callback() {
                                        that.getIndexList();
                                    }
                                })
                                break;
                            case 'edit':
                                Fast.api.open(`groupon/order/store_express/add?store_id=${row.store_id}&express_id=${row.id}`, '编辑', {
                                    callback() {
                                        that.getIndexList();
                                    }
                                })
                                break;
                            case 'detail':
                                Fast.api.open(`groupon/order/store_express/detail/id/${row.id}`, '详情', {
                                    callback() {
                                        that.getIndexList();
                                    }
                                })
                                break;
                            case 'addexpress':
                                that.getExpressCompany();
                                that.expressDetail = row
                                for (key in that.expressData) {
                                    that.expressData[key] = that.expressDetail[key]
                                }
                                break;
                            case 'successexpress':
                                that.expressCompany.forEach(item => {
                                    if (that.expressData.express_name == item.id + '') {
                                        that.expressData.express_name = item.name
                                        that.expressData.express_code = item.code
                                    }
                                })
                                Fast.api.ajax({
                                    url: `groupon/order/store_express/setExpress/express_id/${that.expressDetail.id}`,
                                    loading: false,
                                    type: 'POST',
                                    data: that.expressData,
                                }, function (ret, res) {
                                    that.expressDialog = false;
                                    that.expressDetail = null;
                                    that.expressData = JSON.parse(JSON.stringify(that.expressDataInit))
                                    that.getIndexList();
                                    return false;
                                })
                                break;
                            case 'printing':
                                window.location.href = `store_express/export/id/${row.id}`;
                                break;
                            default:
                                that.expressDialog = false;
                                break;
                        }
                    },
                    screenEmpty() {
                        this.searchForm = JSON.parse(JSON.stringify(this.searchFormInit))
                    },
                    handleSelectionChange(val) {
                        this.multipleSelection = val;
                    },
                    //分页(更换页面显示条数)
                    pageSizeChange(val) {
                        this.offset = 0
                        this.limit = val
                        this.currentPage = 1;
                        this.getIndexList()
                    },
                    //当前是第几页
                    pageCurrentChange(val) {
                        this.offset = (val - 1) * this.limit;
                        this.currentPage = 1;
                        this.getIndexList()
                    },
                    getExpressCompany() {
                        let that = this;
                        Fast.api.ajax({
                            url: 'groupon/express/select',
                            loading: false,
                            type: 'GET',
                            data: {
                                searchWhere: that.selectSearchKey,
                                limit: that.selectLimit,
                                offset: that.selectOffset
                            }
                        }, function (ret, res) {
                            that.expressCompany = res.data.rows;
                            that.selectTotalPage = res.data.total;
                            that.expressDialog = true;
                            that.selectSearchKey = ''
                            return false;
                        })
                    },
                    selectCurrentChange(val) {
                        this.selectOffset = (val - 1) * 6;
                        this.selectLimit = 6;
                        this.selectCurrentPage = 1;
                        this.getExpressCompany();
                    },
                    selectDebounceFilter: debounce(function () {
                        this.getExpressCompany()
                    }, 1000),
                    selectFilter(val) {
                        this.selectSearchKey = val;
                        this.selectLimit = 6;
                        this.selectOffset = 0;
                        this.selectCurrentPage = 1;
                        this.selectDebounceFilter();
                    },
                    arraySpanMethod({
                        row,
                        column,
                        rowIndex,
                        columnIndex
                    }) {
                        if (rowIndex >= 0) {
                            if (columnIndex === 0) {
                                return [, 0];
                            } else if (columnIndex === 1) {
                                return [1, 4];
                            }
                        }
                    },
                    tableCellClassName({
                        columnIndex
                    }) {
                        if (columnIndex == 5) {
                            return 'cell-left';
                        }
                        return '';
                    },
                },
            })
        },
        add: function () {
            function debounce(handle, delay) {
                let time = null;
                return function () {
                    let self = this,
                        arg = arguments;
                    clearTimeout(time);
                    time = setTimeout(function () {
                        handle.apply(self, arg);
                    }, delay)
                }
            }
            var addPage = new Vue({
                el: "#addPage",
                data() {
                    return {
                        screenType: false,
                        orderScreenList: {},
                        orderList: [],
                        multipleSelection: [],
                        express_dialog: false,
                        deliverForm: {
                            item_ids: '',
                            express_name: '',
                            express_code: '',
                            express_no: ''
                        },
                        deliverFormInit: {
                            item_ids: '',
                            express_name: '',
                            express_code: '',
                            express_no: ''
                        },
                        expressCompany: [],
                        disabledBtn: false,
                        //分页
                        currentPage: 1,
                        totalPage: 0,
                        offset: 0,
                        limit: 10,
                        dispatchList: [],
                        dispatchListItem: [],
                        totalStatus: '',
                        optRecordDialog: false,
                        optList: [],
                        focusi: false,

                        //快递公司分页
                        selectSearchKey: '',
                        selectOffset: 0,
                        selectLimit: 6,
                        selectCurrentPage: 1,
                        selectTotalPage: 0,

                        // form搜索
                        searchForm: {
                            status: "nosend",
                            createtime: [],
                            form_1_key: "order_sn",
                            form_1_value: "",
                            platform: "",
                            type: "",
                            pay_type: "",
                            goods_title: "",
                            form_2_key: "user_id",
                            form_2_value: "",

                            store_id: ''
                        },
                        searchFormInit: {
                            status: "nosend",
                            createtime: [],
                            form_1_key: "order_sn",
                            form_1_value: "",
                            platform: "",
                            type: "",
                            pay_type: "",
                            goods_title: "",
                            form_2_key: "user_id",
                            form_2_value: "",

                            store_id: ''
                        },
                        searchOp: {
                            status: "=",
                            createtime: "range",
                            order_sn: "=",
                            id: "=",
                            aftersale_sn: "=",
                            transaction_id: "=",
                            platform: "=",
                            type: "=",
                            pay_type: "=",
                            goods_title: "like",
                            user_id: "=",
                            nickname: "like",
                            user_phone: "like",
                            consignee: "like",
                            phone: "like",

                            store_id: '='
                        },

                        choice_dialog: false,
                        choice_list: [],
                        choice_order_id: null,
                        choice_id: null,

                        selectStoreList: [],
                        searchWhree: '',
                        store_id_switch: false,
                        forceCheck: 1,
                        params_express_id: '',
                        messagehtml: [],
                        pageType: 'add',
                        isAjax: true
                    }
                },
                mounted() {
                    if (new URLSearchParams(location.search).get('express_id')) {
                        this.pageType = 'edit'
                        this.searchForm.status = 'sends'
                        this.searchFormInit.status = 'sends'
                        this.params_express_id = new URLSearchParams(location.search).get('express_id')
                    }
                    if (new URLSearchParams(location.search).get('store_id')) {
                        this.searchForm.store_id = new URLSearchParams(location.search).get('store_id')
                    }
                    this.reqOrderScreenList()
                    this.getstoreOptions();
                    this.reqOrderList()
                },
                methods: {
                    getDetailData() {
                        let that = this;
                        Fast.api.ajax({
                            url: `groupon/order/store_express/detail/id/${that.params_express_id}`,
                            loading: false,
                            type: 'GET',
                        }, function (ret, res) {
                            that.messagehtml = res.data.goods;
                            let arrs = []

                            let item_ids = res.data.item_ids
                            that.orderList.forEach(order => {
                                order.item.forEach(item => {
                                    if (item_ids.includes(item.id)) {
                                        item.checked = true
                                    }
                                })
                                let allSelect = order.item.every(item => {
                                    return item_ids.includes(item.id)
                                })
                                if (allSelect) {
                                    arrs.push(order)
                                }
                                that.forceCheck++
                            });
                            that.$nextTick(() => {
                                arrs.forEach(order => {
                                    that.$refs.multipleTable.toggleRowSelection(order);
                                })
                            })

                            that.handlerOrderList(that.orderList)

                            return false;
                        }, function (ret, res) {
                            that.isAjax = false;
                        })
                    },
                    changeStoreId(val) {
                        if (val) {
                            this.searchForm.store_id = '0';
                        } else {
                            this.searchForm.store_id = '';
                        }
                    },
                    getstoreOptions() {
                        let that = this;
                        Fast.api.ajax({
                            url: 'groupon/store/store/all',
                            loading: false,
                            type: 'GET',
                            data: {
                                search: that.searchWhree,
                            }
                        }, function (ret, res) {
                            that.selectStoreList = res.data;
                            that.searchWhree = ""
                            return false;
                        })
                    },
                    sdebounceFilter: debounce(function () {
                        this.getstoreOptions()
                    }, 1000),
                    dataFilter(val) {
                        this.searchWhree = val;
                        this.sdebounceFilter()
                    },
                    //筛选
                    changeSwitch() {
                        this.screenType = !this.screenType;
                    },
                    reqOrderScreenList() {
                        var that = this;
                        Fast.api.ajax({
                            url: 'groupon/order/order/getType',
                            loading: false,
                            type: 'GET',
                        }, function (ret, res) {
                            that.orderScreenList = res.data
                            return false;
                        })
                    },
                    //请求
                    reqOrderList() {
                        var that = this;
                        if (that.searchForm.store_id == '') {
                            this.$notify({
                                title: '警告',
                                message: '自提点必选',
                                type: 'warning'
                            });
                            that.isAjax = false
                            return false;
                        } else {
                            that.isAjax = true
                        }
                        let filter = {}
                        let op = {}
                        for (key in that.searchForm) {
                            if (key != 'status' && key != 'createtime' && key != 'form_1_key' && key != 'form_1_value' && key != 'form_2_key' && key != 'form_2_value') {
                                if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                    filter[key] = that.searchForm[key];
                                }
                            } else if (key == 'form_1_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_1_key] = that.searchForm[key];
                                }
                            } else if (key == 'form_2_value') {
                                if (that.searchForm[key] != '') {
                                    filter[that.searchForm.form_2_key] = that.searchForm[key];
                                }
                            } else if (key == 'createtime') {
                                if (that.searchForm[key]) {
                                    if (that.searchForm[key].length > 0) {
                                        filter[key] = that.searchForm[key].join(' - ');
                                    }
                                }
                            } else if (key == 'status') {
                                if (that.searchForm[key] != '' && that.searchForm[key] != 'all') {
                                    filter[key] = that.searchForm[key];
                                }
                            }
                        }
                        for (key in filter) {
                            op[key] = that.searchOp[key]
                        }
                        Fast.api.ajax({
                            url: 'groupon/order/order/index',
                            loading: false,
                            type: 'GET',
                            data: {
                                filter: JSON.stringify(filter),
                                op: JSON.stringify(op),
                                offset: 0,
                                limit: 9999999999,
                            }
                        }, function (ret, res) {
                            that.orderList = res.data.rows;
                            that.orderList.forEach(order => {
                                order.item.forEach(item => {
                                    item.checked = false
                                })
                            })
                            if (that.pageType == 'edit') {
                                that.getDetailData()
                            } else {
                                that.isAjax = false
                            }
                            that.focusi = false;
                            return false;
                        })
                    },
                    screenEmpty() {
                        this.searchForm = JSON.parse(JSON.stringify(this.searchFormInit))
                    },
                    goDetail(id) {
                        let that = this;
                        Fast.api.open('groupon/order/order/detail?id=' + id, "查看详情", {
                            callback() {
                                that.reqOrderList()
                            }
                        });
                    },
                    goGroupon(type, id) {
                        let that = this;
                        if (id == 0) {
                            return false;
                        }
                        if (type == "groupon") {
                            parent.Fast.api.open(`groupon/activity/groupon/detail/id/${id}`, "查看详情", {
                                callback(data) {
                                    that.reqOrderList()
                                }
                            });
                        }
                    },
                    goOrderUser(id) {
                        let that = this;
                        Fast.api.open('groupon/user/user/profile?id=' + id, '查看下单用户', {
                            callback() {
                                that.reqOrderList();
                            }
                        })
                    },
                    optRecord(id) {
                        let that = this;
                        Fast.api.ajax({
                            url: `groupon/order/order/actions/id/${id}`,
                            loading: true,
                            data: {}
                        }, function (ret, res) {
                            that.optList = res.data;
                            that.optRecordDialog = true
                            return false;
                        })
                    },
                    goOrderRefresh() {
                        this.focusi = true;
                        this.reqOrderList()
                    },
                    arraySpanMethod({
                        rowIndex,
                        columnIndex
                    }) {
                        if (rowIndex >= 0) {
                            if (columnIndex === 0) {
                                return [0, 1];
                            } else if (columnIndex === 1) {
                                return [1, 2];
                            }
                        }
                    },
                    singleSelectRow(selection, row) {
                        let id = row.id
                        let isselection = selection.some(order => {
                            return order.id == row.id
                        })
                        this.orderList.forEach(order => {
                            if (order.id == id) {
                                order.item.forEach(item => {
                                    if (isselection) {
                                        item.checked = true
                                    } else {
                                        item.checked = false
                                    }
                                })
                            }
                        })
                        this.handlerOrderList(this.orderList)
                    },
                    allSelectRow(selection) {
                        this.orderList.forEach(order => {
                            order.item.forEach(item => {
                                if (selection.length > 0) {
                                    item.checked = true
                                } else {
                                    item.checked = false
                                }
                            })
                        })
                        this.handlerOrderList(this.orderList)
                        if (selection.length == 0) {
                            this.$refs.multipleTable.clearSelection();
                        }
                    },
                    handleSelectionChange(val) {
                        this.multipleSelection = val
                    },
                    orderItemSelected(index, innerindex, checked) {
                        this.orderList[index].item[innerindex].checked = checked;
                        this.$set(this.orderList[index].item[innerindex], 'checked', checked)
                        let allChecked = this.orderList[index].item.every(item => {
                            return item.checked == true
                        })
                        if (allChecked) {
                            this.$refs.multipleTable.toggleRowSelection(this.orderList[index]);
                        } else {
                            let allCheckeds = this.orderList[index].item.some(item => {
                                return item.checked == false
                            })
                            if (allCheckeds) {
                                let arrs = []
                                this.multipleSelection.forEach((order, oindex) => {
                                    if (oindex != index) {
                                        arrs.push(order)
                                    }
                                })
                                this.$refs.multipleTable.clearSelection();
                                arrs.forEach(order => {
                                    this.$refs.multipleTable.toggleRowSelection(order);
                                })
                            }
                        }
                        this.handlerOrderList(this.orderList)
                        this.forceCheck++;
                        this.$forceUpdate();
                    },
                    stockList() {
                        let that = this;
                        let item_ids = []
                        this.orderList.forEach(order => {
                            order.item.forEach(item => {
                                if (item.checked) {
                                    item_ids.push(item.id)
                                }
                            })
                        })
                        let reqUrl = `groupon/order/store_express/send/store_id/${that.searchForm.store_id}`
                        if (that.params_express_id) {
                            reqUrl = `groupon/order/store_express/send/store_id/${that.searchForm.store_id}/express_id/${that.params_express_id}`
                        }
                        Fast.api.ajax({
                            url: reqUrl,
                            loading: false,
                            type: 'POST',
                            data: {
                                item_ids: item_ids
                            }
                        }, function (ret, res) {
                            Fast.api.close()
                            return false;
                        })
                    },
                    handlerOrderList(newVal) {
                        let selectedArr = []
                        let val = JSON.parse(JSON.stringify(newVal))
                        val.forEach(order => {
                            order.item.forEach(item => {
                                if (item.checked) {
                                    let isgoods_id = selectedArr.some(select => {
                                        return item.goods_id == select.goods_id && item.goods_sku_price_id == select.goods_sku_price_id
                                    })
                                    if (!isgoods_id) {
                                        selectedArr.push(item)
                                    } else {
                                        selectedArr.forEach(select => {
                                            if (item.goods_id == select.goods_id && item.goods_sku_price_id == select.goods_sku_price_id) {
                                                select.goods_num = Number(select.goods_num) + Number(item.goods_num)
                                            }
                                        })
                                    }
                                }
                            })
                        })
                        this.messagehtml = selectedArr;
                        this.isAjax = false;
                    }
                },
            })
        },
        detail: function () {
            function debounce(handle, delay) {
                let time = null;
                return function () {
                    let self = this,
                        arg = arguments;
                    clearTimeout(time);
                    time = setTimeout(function () {
                        handle.apply(self, arg);
                    }, delay)
                }
            }
            var detailPage = new Vue({
                el: "#detailPage",
                data() {
                    return {
                        orderList: [],
                        packageLog: [],
                        packageActive: 0,
                        dashboardList: [],
                        isAjax: true,
                        packageAjax: false,
                        deliverForm: {
                            express_name: '',
                            express_no: '',
                            updatetime: ''
                        },
                        storeForm: {
                            name: '',
                            realname: '',
                            phone: '',
                            province_name: '',
                            city_name: '',
                            area_name: '',
                            address: ''
                        },

                        optRecordDialog: false,
                        optList: [],
                    }
                },
                mounted() {
                    this.getDetailData();
                },
                methods: {
                    getDetailData() {
                        let that = this;
                        if (!that.isAjax) {
                            that.packageAjax = true;
                        }
                        Fast.api.ajax({
                            url: `groupon/order/store_express/detail/id/${Config.id}`,
                            loading: false,
                            type: 'GET',
                        }, function (ret, res) {
                            that.orderList = res.data.orders;
                            that.packageLog = res.data.row.log;
                            that.dashboardList = res.data.goods;
                            for (key in that.deliverForm) {
                                that.deliverForm[key] = res.data.row[key]
                            }
                            if (res.data.row.store) {
                                for (key in that.storeForm) {
                                    that.storeForm[key] = res.data.row.store[key]
                                }
                            }
                            that.isAjax = false;
                            that.packageAjax = false;
                            return false;
                        }, function (ret, res) {
                            that.isAjax = false;
                            that.packageAjax = false;
                        })
                    },
                    operation(type) {
                        let that = this;
                        Fast.api.ajax({
                            url: `groupon/order/store_express/getExpress/express_id/${Config.id}`,
                            loading: false,
                            type: 'GET',
                            data: {
                                type: type
                            }
                        }, function (ret, res) {
                            that.getDetailData();
                        })
                    },
                    goDetail(id) {
                        let that = this;
                        Fast.api.open('groupon/order/order/detail?id=' + id, "查看详情");
                    },
                    goGroupon(type, id) {
                        let that = this;
                        if (id == 0) {
                            return false;
                        }
                        if (type == "groupon") {
                            parent.Fast.api.open(`groupon/activity/groupon/detail/id/${id}`, "查看详情");
                        }
                    },
                    goOrderUser(id) {
                        let that = this;
                        Fast.api.open('groupon/user/user/profile?id=' + id, '查看下单用户')
                    },
                    optRecord(id) {
                        let that = this;
                        Fast.api.ajax({
                            url: `groupon/order/order/actions/id/${id}`,
                            loading: true,
                            data: {}
                        }, function (ret, res) {
                            that.optList = res.data;
                            that.optRecordDialog = true
                            return false;
                        })
                    },
                },
            })
        },
    };
    return Controller;
});